<template>
  <div class="menber">
    <div class="commontop">
      <div class="commontop-left">
        <el-input
          v-model="pages.name"
          placeholder="请输入姓名或者手机号"
          @change="INput"
          @clear="INput"
          @keyup.enter.native="goSearch()"
          clearable
          prefix-icon="el-icon-search"
        ></el-input>
        <el-button
          class="searchbgc"
          @click="goSearch"
          icon="iconfont icon-sousuo2"
          >搜索</el-button
        >
        <router-link
          :to="{
            path: '/user/user-registration',
            query: {
              id: '2',
            },
          }"
          ><el-button
            v-show="xsyc === '1' ? true : false"
            icon="iconfont icon-zhanghao-xuanzhong1"
            >注册</el-button
          ></router-link
        >
        <el-button
          icon="iconfont icon-piliangdaoruyonghu2"
          v-show="xsyc === '1' ? true : false"
          @click="drawer = true"
          >批量导入用户</el-button
        >
      </div>
      <div class="commontop-right">
        <el-button
          icon="iconfont icon-daochu1"
          @click="Goexport"
          v-show="xsyc === '1' ? true : false"
          >导出</el-button
        >
        <el-button
          v-show="xsyc === '1' ? true : false"
          class="red"
          icon="iconfont icon-shanchu1"
          @click="deleteSelectItem()"
          >删除</el-button
        >
      </div>
    </div>
    <el-table
      class="table"
      ref="multipleSelection"
      v-loading="isLoading"
      element-loading-spinner="el-icon-loading"
      element-loading-text="玩命加载中"
      max-height="645"
      :data="tableData"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ backgroundColor: '#3963fd', color: '#fff' }"
      style="width: 100%; margin-top: 20px"
    >
      <template slot="empty">
        <img src="@/assets/imgs/暂未数据.png" alt style="margin-top: 104px" />
        <p style="margin-top: 15px; margin-bottom: 104px">暂未有数据</p>
      </template>
      <el-table-column type="selection"></el-table-column>
      <el-table-column
        prop="id"
        label="序号"
        width="80"
        sortable
      ></el-table-column>
      <el-table-column
        prop="nickname"
        width="90"
        label="姓名"
      ></el-table-column>
      <el-table-column
        prop="roles"
        width="140"
        :show-overflow-tooltip="true"
        label="角色"
      ></el-table-column>
      <el-table-column
        prop="phone"
        label="手机"
        width="115px"
      ></el-table-column>
      <el-table-column prop="no_hash_pwd" label="密码"></el-table-column>
      <el-table-column
        prop="companies"
        :show-overflow-tooltip="true"
        label="所属公司"
      ></el-table-column>
      <el-table-column
        prop="departments"
        :show-overflow-tooltip="true"
        label="部门"
      ></el-table-column>
      <el-table-column
        prop="project"
        :show-overflow-tooltip="true"
        label="对应项目"
      ></el-table-column>
      <el-table-column
        prop="part_companie"
        :show-overflow-tooltip="true"
        label="参建单位"
      ></el-table-column>
      <el-table-column label="状态" width="90">
        <template slot-scope="scope">
          <el-tag v-if="tableData[scope.$index].deleted_at > 0" type="danger"
            >已删除</el-tag
          >
          <el-tag v-else-if="tableData[scope.$index].status == 1">正常</el-tag>
          <el-tag v-else-if="tableData[scope.$index].status == 0" type="info"
            >未审核</el-tag
          >
          <el-tag v-else-if="tableData[scope.$index].status == 2" type="warning"
            >禁用</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="100px">
        <template
          slot-scope="scope"
          v-if="scope.row.is_super_admin == 1 ? false : true"
        >
          <!-- v-if="scope.row.value == true ? true : false" -->
          <el-tooltip content="编辑" placement="top">
            <el-button class="green" size="mini" @click="handleEdit(scope.row)"
              ><i class="el-icon-edit"></i
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              class="red"
              size="mini"
              @click="handleDelete(scope.row.id)"
              ><i class="el-icon-delete"></i
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current_page"
        :page-sizes="pageSizeArr"
        :page-size="pages.per_page"
        layout="total, sizes, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-drawer
      title="批量导入用户"
      :visible.sync="drawer"
      :wrapperClosable="false"
    >
      <common-dawer :num="1"></common-dawer>
    </el-drawer>
    <el-dialog
      class="tab"
      title="编辑"
      width="25%"
      :visible.sync="dialogFormVisible"
    >
      <el-form :model="editForm" ref="editForm">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input
            placeholder="请输入姓名"
            v-model="editForm.nickname"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
          <el-tree
            ref="tree"
            :data="companies"
            show-checkbox
            node-key="id"
            @check="treeCheckNode"
            :default-checked-keys="deptKey"
            :props="defaultProps2"
          >
          </el-tree>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-radio-group v-model="editForm.status">
            <el-radio :label="2">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">未审核</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editModify('editForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  users,
  Searchusers,
  usersdel,
  usersModify,
  destroyMore,
  usersQuery,
  usersTree,
} from "../../api/recycle/index";
import commonInfo from "@/utils/common";
import fileDownload from "js-file-download";
import CommonDawer from "../../components/common/commonDawer.vue";
/* import { use } from 'vue/types/umd'; */
/* import { handleEdit2 } from "../../assets/Js/menber"; */
export default {
  components: {
    CommonDawer,
  },
  data() {
    return {
      //按钮显示隐藏
      xsyc: "1",
      pages: {
        per_page: 10,
        page: 1,
        name: "",
      },
      //表格页面
      pageSizeArr: JSON.parse(JSON.stringify(commonInfo.pageSizeArr)),
      current_page: 1,

      total: 0,
      isLoading: true,
      //批量导入
      drawer: false,

      //表格
      multipleSelection: [],
      /* 表格数据 */
      tableData: [],

      //编辑蒙尘
      dialogFormVisible: false,
      /* 编辑表单 */
      editForm: {
        nickname: "",
        sex: "",
        roles: [],
        phone: "",
        status: 2,
      },
      /* 角色的数组 */
      companies: [],
      /* 角色选中状态 */
      deptKey: [],
      /* 权限id */
      permissionsId: [],
      formLabelWidth: "15%",
      defaultProps2: {
        children: "roles",
        label: "title",
      },
    };
  },
  methods: {
    INput() {
      if (this.pages.name == "") {
        this.loadData();
      }
    },
    //搜索
    async goSearch() {
      this.pages.page = 1;
      this.pages.per_page = 10;
      this.current_page = 1;
      console.log(this.pages);
      if (this.pages.name == "") {
        this.$message.warning("查询条件不能为空！");
        return;
      }
      let res = await Searchusers(this.pages);
      console.log(res, "123");
      this.tableData = res.data.data.data;
      this.current_page = res.data.data.current_page;
      this.per_page = res.data.data.per_page;
      this.total = res.data.data.total;
      for (let item1 of this.tableData) {
        for (let item2 of res.data.data.data) {
          if (item1.id == item2.id) {
            let roleslist = item2.roles.map((i) => {
              return i.title;
            });
            let company = item2.companies.map((i) => {
              return i.title;
            });
            let department = item2.departments.map((i) => {
              return i.title;
            });
            let project = item2.projects.map((i) => {
              return i.title;
            });
            let part_companie = item2.part_companies.map((i) => {
              return i.title;
            });
            //console.log(roleslist);
            item1.roles = roleslist.join("、");
            item1.companies = company.join("、");
            item1.project = project.join("、");
            item1.part_companie = part_companie.join("、");
            item1.departments = department.join("、");
          }
        }
      }
      console.log(this.tableData);
    },
    /* 获取表格信息 */
    async loadData(num) {
      let res = await users(num);
      console.log(res, "123");
      this.tableData = res.data.data.data;
      this.isLoading = false;
      this.current_page = res.data.data.current_page;
      this.per_page = res.data.data.per_page;
      this.total = res.data.data.total;
      for (let item1 of this.tableData) {
        for (let item2 of res.data.data.data) {
          if (item1.id == item2.id) {
            let roleslist = item2.roles.map((i) => {
              return i.title;
            });
            let company = item2.companies.map((i) => {
              return i.title;
            });
            let department = item2.departments.map((i) => {
              return i.title;
            });
            let project = item2.projects.map((i) => {
              return i.title;
            });
            let part_companie = item2.part_companies.map((i) => {
              return i.title;
            });
            //console.log(roleslist);
            item1.roles = roleslist.join("、");
            item1.companies = company.join("、");
            item1.project = project.join("、");
            item1.part_companie = part_companie.join("、");
            item1.departments = department.join("、");
          }
        }
      }
    },
    // 本地文件下载
    aDown() {
      let link = document.createElement("a");
      link.setAttribute("href", "./static/excelTemplate.xlsx");
      link.setAttribute("download", `批量导入用户模板`);
      link.click();
    },
    //编辑查询
    async handleEdit(row) {
      console.log(row);
      let id = row.id;
      let res = await usersQuery({ id });
      console.log(res, "11");
      this.editForm.id = res.data.data.id;
      this.editForm.phone = res.data.data.phone;
      this.editForm.nickname = res.data.data.nickname;
      this.editForm.status = res.data.data.status;
      this.companies = res.data.data.companies;
      console.log(this.editForm, "112");
      let Check = this.companies;
      let aps = [];
      Check.map((item) => {
        item.roles.map((i) => {
          if (i.select == 1) {
            aps.push(i.id);
          }
          return i;
        });
      });
      this.deptKey = aps;
      this.dialogFormVisible = true;
    },
    // 树状图节点改变时
    treeCheckNode(nodeObject, checkObject) {
      console.log(nodeObject, checkObject);
      console.log(checkObject.checkedKeys);
      this.permissionsId = checkObject.checkedKeys;
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
      //console.log(this.multipleSelection);
    },
    //多选删除
    deleteSelectItem() {
      if (this.multipleSelection == null) {
        this.$message({
          showClose: true,
          duration: 3000,

          message: "请先选中要删除的数据哦！ 亲",
          type: "error",
        });
      } else {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(async () => {
          let arr = this.multipleSelection.map((item) => item.id);
          // console.log(arr);
          let ids = arr.join(",");
          // console.log(ids);
          let res = await destroyMore({ ids });
          // console.log(res);
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "success",
            });
            this.loadData();
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "error",
            });
          }
        });
      }
    },
    /* 导出成员 */
    Goexport() {
      this.$axios({
        method: "get",
        url: "/api/users/export",
        headers: {
          Token: localStorage.getItem("token"),
        },
        data: {},
        responseType: "blob",
      }).then((res) => {
        console.log(res);
        fileDownload(res.data, "成员.xlsx");
      });
    },

    //删除
    handleDelete(id) {
      this.$confirm("确认删除？").then(async () => {
        let res = await usersdel({ id });
        //console.log(res);
        if (res.data.code === 200) {
          this.$message({
            showClose: true,
            duration: 3000,
            message: res.data.msg,
            type: "success",
          });
          this.loadData();
        } else {
          this.$message({
            showClose: true,
            duration: 3000,
            message: res.data.msg,
            type: "error",
          });
        }
      });
    },
    //编辑成功
    editModify(formName) {
      console.log(this.editForm);
      this.editForm.roles = this.permissionsId;
      this.$refs[formName].validate(async (valid) => {
        //console.log(valid);
        if (valid) {
          let res = await usersModify(this.editForm);
          //console.log(res);
          console.log(res.data, "1123");
          if (res.data.code === 200) {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "success",
            });
            this.loadData();
            this.dialogFormVisible = false;
          } else {
            this.$message({
              showClose: true,
              duration: 3000,
              message: res.data.msg,
              type: "error",
            });
          }
        }
      });
    },
    //分页
    handleCurrentChange(val) {
      this.current_page = val;
      this.pages.page = val;
      this.loadData(this.pages);
    },
    //分页
    handleSizeChange(val) {
      this.pages.per_page = val;
      this.loadData(this.pages);
    },
    //树形节点被点击回调
    handleNodeClick(data) {
      console.log(data);
    },
  },
  created() {
    this.loadData();
  },
};
</script>

<style scoped lang="less">
/deep/.el-table__header {
  margin-bottom: 20px;
}
/deep/.el-table {
  background-color: #f3f5fb;
}
/deep/.el-table .cell {
  display: flex;
}
/deep/.el-button--mini {
  font-size: 18px !important;
}

.el-button--mini {
  padding: 6px 3px;
}
</style>